// pages/loading/loading.js
import { GetWechatSessionApi, UserLoginStatus } from '../../api/login.js';
import { CurrentUser } from '../../api/user.js';
import { setToken } from '../../api/request.js';

const app = getApp();

Page({

  data: {
    motto: '登陆中...',
    userInfo: null,
    showModal: false,
    canIUse: wx.canIUse('button.open-type.getUserInfo')
  },
  //事件处理函数
  bindViewTap: function (e) {

  },
  onLoad: function () {
    wx.login({
      success: resp => {
        app.globalData.jsCode = resp.code;
        // 获取用户信息
        wx.getSetting({
          success: res => {
            if (res.authSetting['scope.userInfo']) {
              // 已经授权，可以直接调用 getUserInfo 获取头像昵称，不会弹框
              wx.getUserInfo({
                success: res => {
                  // 可以将 res 发送给后台解码出 unionId
                  app.globalData.userInfo = res.userInfo
                  this.setData({
                    userInfo: res.userInfo,
                  });
                  this.naviagate({ jsCode: app.globalData.jsCode })
                }
              })
            } else if (this.data.canIUse) {
              app.globalData.unauthorized = true;
              this.setData({
                showModal: true,
              });
            } else {
              // 在没有 open-type=getUserInfo 版本的兼容处理
              wx.getUserInfo({
                success: res => {
                  app.globalData.userInfo = res.userInfo
                  this.setData({
                    userInfo: res.userInfo,
                  });
                  this.naviagate({ jsCode: app.globalData.jsCode });
                }
              })
            }
          }
        });
      },
      fail(err) {
        console.log(err);
        wx.showToast({ title: '微信登录失败', icon: 'none', duration: 2000 });
      }
    });
  },
  naviagate(params) {
    GetWechatSessionApi(params)
      .then(data => {
        const openid = data.openid;
        app.globalData.wxOpenId = openid;
        wx.setStorage({
          key: 'wxOpenId',
          data: openid,
        });
        return UserLoginStatus({ openId: openid });
      })
      .then(data => {
        if (data === 'NotExists') {
          app.globalData.token = null;
          setToken(null);
          wx.removeStorageSync('token');
          wx.reLaunch({ url: '/pages/register/entry/entry' });
        } if (data === 'Unlogined') {
          app.globalData.token = null;
          setToken(null);
          wx.removeStorageSync('token');
          wx.reLaunch({ url: '/pages/register/register/register' });
        } else if (data === 'Logined') {
          return CurrentUser({});
        } else {

        }
      })
      .then(data => {
        if (data !== undefined && data !== null) {
          app.globalData.currentUserInfo = data;
          setTimeout(() => {
            if ('CUSTOMER' === data.userType) {
              wx.reLaunch({ url: '/pages/user/home/home' });
            } else if ('MERCHANT' === data.userType) {
              wx.reLaunch({ url: '/pages/merchant/home/home' });
            }
          }, 1000);
        }
      })
      .catch(err => {
        console.log(err)
        wx.showToast({ title: '服务器被大风吹跑了', icon: 'none', duration: 2000 });
      })
  },
  getUserInfo: function (e) {
    app.globalData.userInfo = e.detail.userInfo
    app.globalData.unauthorized = false;
    this.setData({
      userInfo: e.detail.userInfo,
      showModal: false,
    });
    this.naviagate({ jsCode: app.globalData.jsCode });
  }
});